//
//  RedioHostViewController.m
//  Atlantis
//
//  Created by 何恩营 on 14-12-17.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

// 播主页面
#import "RedioHostViewController.h"
#import "MusicCell.h"
#import "AlbumCell.h"
#import "NetHandler.h"
#import "Music.h"
#import "List.h"
#import "UIImageView+WebCache.h"
#import "AlbumDetailsViewController.h"
#import "PlayViewController.h"

#import "UIScrollView+MJRefresh.h"
#import "UIScrollView+Extension.h"

// 宏定义
#define kAlbumReuse @"albumReuse"
#define kMusicReuse @"musicReuse"


@interface RedioHostViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate>

// 表视图
@property(nonatomic, retain) UITableView *tableView;
// 播主简介
@property(nonatomic, retain) UILabel *introLabel;
// 播主名称
@property(nonatomic, retain) UILabel *nickNameLabel;
// 播主头像
@property(nonatomic, retain) UIImageView *imageView;
@property(nonatomic, retain) UIView *contentView;
// 数据
// 音频列表对象
@property(nonatomic, retain) List *trackList;
// 专辑列表对象
@property(nonatomic, retain) List *albumList;
// 当前请求页数
@property(nonatomic, assign) NSInteger page;


@end

@implementation RedioHostViewController

- (void)dealloc
{
    // album对象
    [_album release];
    // 表视图
    [_tableView release];
    // 播主简介
    [_introLabel release];
    // 播主名称
    [_nickNameLabel release];
    // 播主头像
    [_imageView release];
    [_contentView release];
    [_trackList release];
    [_albumList release];
    [super dealloc];
}


// 下拉刷新, 上拉加载更多
- (void)setupRefresh
{
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
}
//   进入加载状态
- (void)footerRereshing
{
    self.page += 1;
    //1. 拼接口等操作
    // 请求加载数据
    [self footerHandleData];
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableView reloadData];
        [self.tableView footerEndRefreshing];
    });
}

// 处理数据
- (void)handleData
{
    // 专辑请求接口
    NSString *albumStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/album/%@/1/2?device=iPhone", self.album.uid];
    // 音频请求接口
    NSString *trackStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%@/1/30?device=iPhone", self.album.uid];
    
    // 专辑 网络请求
    [NetHandler getDataWithURL:albumStr completion:^(NSData *data) {
        // json解析
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
        self.albumList = [[List alloc] initWithDictionary:result];
        NSArray *arr = [result objectForKey:@"list"];
        
        // 遍历数组
        for (NSDictionary *dic in arr) {
            // 利用字典给对象赋值
            Album *album = [[Album alloc] initWithDictionary:dic];
            [self.albumList.listArr addObject:album];
            [album release];
        }
        
        [_albumList release];
        // tableView重新加载数据
        [self.tableView reloadData];
        
    }];
    
    // 音频网络请求
    [NetHandler getDataWithURL:trackStr completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.trackList = [[List alloc] initWithDictionary:result];
        NSArray *listArr = [result objectForKey:@"list"];
        // 遍历数组
        for (NSDictionary *dic in listArr) {
            Music *music = [[Music alloc] initWithDictionary:dic];
            [self.trackList.listArr addObject:music];
            [music release];
        }
        [_trackList release];
        [self.tableView reloadData];
        [self setupRefresh];
    }];
}

// 上拉加载数据
- (void)footerHandleData
{
    NSString *trackStr = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/others/ca/track/%@/%ld/30?device=iPhone", self.album.uid, self.page];
    [NetHandler getDataWithURL:trackStr completion:^(NSData *data) {
        
        id result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *listArr = [result objectForKey:@"list"];
        for (NSDictionary *dic in listArr) {
            Music *music = [[Music alloc] initWithDictionary:dic];
            [self.trackList.listArr addObject:music];
            [music release];
        }
        [self.tableView reloadData];
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.s
    
    
    // 导航栏标题
    self.navigationItem.title = @"访问播主";
    
    
    
    // 初始化当前数据请求页数为1
    self.page = 1;
    // 调用数据请求方法
    [self handleData];
    
    // 创建UIview, 承载几个小控件
    self.contentView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 180)];
    // 设置背景颜色  黑色
    self.contentView.backgroundColor = [UIColor blackColor];
    // 释放内存
    [_contentView release];
    
    // 创建播主头像imageView
    self.imageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.contentView.frame.size.width / 2 - 40, 20, 80, 80)];
    // 设置背景颜色为白色
    self.imageView.backgroundColor = [UIColor whiteColor];
    // 将播主头像imageView, 添加到contentView上
    [self.contentView addSubview:self.imageView];
    // 将imageView图层弄成圆形
    self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
    self.imageView.layer.masksToBounds = YES;
    // 给图片视图赋值图片
    [self.imageView setImageWithURL:[NSURL URLWithString:self.album.avatarPath]];
    // 释放内存
    [_imageView release];
    
    // 创建播主名称Label
    self.nickNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 100, self.contentView.bounds.size.width, 40)];
    // 将播主Label添加到contentView上
    [self.contentView addSubview:self.nickNameLabel];
    // 设置nickName的文字颜色设置为白色
    self.nickNameLabel.textColor = [UIColor whiteColor];
    // 给Label, text赋值
    self.nickNameLabel.text = self.album.nickname;
    // 设置文字大小
    self.nickNameLabel.font = [UIFont boldSystemFontOfSize:24];
    // 设置对齐方式  居中对齐
    self.nickNameLabel.textAlignment = NSTextAlignmentCenter;
    // 内存释放
    [_nickNameLabel release];
    
    // 博主简介
    self.introLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 140, self.contentView.bounds.size.width, 20)];
    // 视图加载
    [self.contentView addSubview:self.introLabel];
    // 背景颜色
    self.introLabel.textColor = [UIColor whiteColor];
    // 赋值
    self.introLabel.text = self.album.intro;
    // 字体居中
    self.introLabel.textAlignment = NSTextAlignmentCenter;
    // 内存管理
    [_introLabel release];
    
    // 表视图
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    // 给tableView指定代理人
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    // 视图加载
    [self.view addSubview:self.tableView];
    // 头标题赋值
    self.tableView.tableHeaderView = self.contentView;
    // 内存管理
    [_tableView release];
    
    // 给tableView注册cell
    
    // albumCell 专辑自定义cell
    [self.tableView registerClass:[AlbumCell class] forCellReuseIdentifier:kAlbumReuse];
    // musicCell 音乐自定义cell
    [self.tableView registerClass:[MusicCell class] forCellReuseIdentifier:kMusicReuse];
    
    // 导航栏左侧返回按钮
    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"return.png"] style:UIBarButtonItemStyleDone target:self action:@selector(collectionAction:)] autorelease];
}



// 导航栏左侧返回按钮触发事件
- (void)collectionAction:(UINavigationBar *)bar
{
    //NSLog(@"返回前一页");
    // 推出前一页
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark tableView协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // 判断当前section是专辑区, 还是音频区
    if (section == 0) {
        // 如果是专辑区, 返回专辑数组的长度
        return self.albumList.listArr.count;
    } else {
        // 音频区, 返回音频数组的长度
        return self.trackList.listArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        AlbumCell *cell = [tableView dequeueReusableCellWithIdentifier:kAlbumReuse];
        // 给cell的alb属性赋值
        cell.alb = [self.albumList.listArr objectAtIndex:indexPath.row];
        
        return cell;
    } else {
        MusicCell *cell = [tableView dequeueReusableCellWithIdentifier:kMusicReuse];
        // 给cell的music属性赋值
        cell.music = [self.trackList.listArr objectAtIndex:indexPath.row];
        return cell;
    }
}

// section的个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}
// section标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    // 判断是专辑区域, 还是音频区域
    if (section == 0) {
        // 专辑区返回
        return [NSString stringWithFormat:@"发布的专辑 (%@)", self.albumList.totalCount];
    } else {
        // 音频区返回
        return [NSString stringWithFormat:@"发布的声音 (%@)", self.trackList.totalCount];
    }
}

// cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 150;
    } else {
        return 120;
    }
}


// 点击cell执行方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 判断点击的是专辑, 还是音频
    if (indexPath.section == 0) {
        // 如果是专辑, 则跳转专辑详情页面
        AlbumDetailsViewController *albumDetailVC = [[AlbumDetailsViewController alloc] init];
        // 给专辑详情页传值
        albumDetailVC.album = [self.albumList.listArr objectAtIndex:indexPath.row];
        // push推出专辑详情页
        [self.navigationController pushViewController:albumDetailVC animated:YES];
        [albumDetailVC release];
    } else {
        // 创建播放视图
        PlayViewController *playVC = [PlayViewController sharePlayVC];
        
        // 获取对象值
        Music *music = [self.trackList.listArr objectAtIndex:indexPath.row];
        // 判断是否为同一播放对象
        if (![playVC.music.trackId isEqual:music.trackId]) {
            // 赋值
            playVC.musicArr = self.trackList.listArr;
            playVC.currentMusic = indexPath.row;
            // 播放页面
            [playVC play];
        }
        // 推出界面
        [self.navigationController pushViewController:playVC animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
